import { UserProfile } from '../../auth/types';
import { API_PATHS } from '../../../config/apiConfig';

const API_BASE = API_PATHS.promotions;

export interface Promotion {
  id: string;
  promotionId?: string; // 添加promotionId字段
  promotionTitle: string;
  promotionRule: string;
  startTime: string;
  endTime: string;
  isActive: boolean;
  discount: number;
  createdAt: string;
  updatedAt: string;
  inProgress?: boolean; // 添加 inProgress 字段，表示活动是否正在进行中
}

export interface PromotionListResponse {
  promotions: Promotion[];
  total: number;
  page: number;
  pageSize: number;
}

export class PromotionService {
  private static getHeaders(includeAuth: boolean = true) {
    const headers: Record<string, string> = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };

    if (includeAuth) {
      const token = localStorage.getItem('token');
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    return headers;
  }

  static async createPromotion(promotion: { 
    title: string; // 用作promotionTitle
    promotionRule: string;
    startTime: string; 
    endTime: string; 
    isActive?: boolean;
    discount: number;
  }): Promise<Promotion> {
    // 根据用户提供的请求体格式构建数据
    const requestData = {
      promotionTitle: promotion.title,
      promotionRule: promotion.promotionRule,
      startTime: promotion.startTime,
      endTime: promotion.endTime,
      isActive: promotion.isActive !== undefined ? promotion.isActive : true,
      discount: promotion.discount
    };

    const response = await fetch(`${API_BASE}`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(requestData)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '创建活动失败');
    }

    return response.json();
  }

  static async getPromotionList(page: number = 1, pageSize: number = 10): Promise<PromotionListResponse> {
    const response = await fetch(`${API_BASE}?page=${page}&pageSize=${pageSize}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取活动列表失败');
    }

    return response.json();
  }

  static async getAllPromotions(): Promise<Promotion[]> {
    const response = await fetch(`${API_BASE}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取所有活动失败');
    }

    return response.json();
  }

  static async getActivePromotions(): Promise<Promotion[]> {
    const response = await fetch(`${API_BASE}/active`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取活动活动失败');
    }

    return response.json();
  }

  static async getInProgressPromotions(): Promise<Promotion[]> {
    const response = await fetch(`${API_BASE}/in-progress`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取进行中活动失败');
    }

    return response.json();
  }

  static async updatePromotion(id: string, promotion: Partial<Promotion>): Promise<Promotion> {
    // 确保id不为空
    if (!id) {
      throw new Error('促销活动ID不能为空');
    }

    // 构建请求数据，确保包含promotionId字段
    const requestData = {
      promotionId: parseInt(id),  // 将id转换为整数类型
      ...promotion
    };

    const response = await fetch(`${API_BASE}`, {
      method: 'PUT', // 使用PUT方法
      headers: this.getHeaders(),
      body: JSON.stringify(requestData)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '更新活动失败');
    }

    return response.json();
  }

  static async deletePromotion(id: string): Promise<void> {
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除活动失败');
    }
  }

  static async updatePromotionStatus(id: string, isActive: boolean): Promise<Promotion> {
    const response = await fetch(`${API_BASE}/${id}/status`, {
      method: 'PATCH',
      headers: this.getHeaders(),
      body: JSON.stringify({ promotionId: parseInt(id), isActive })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '更新活动状态失败');
    }

    return response.json();
  }

  static async getPromotionById(id: string): Promise<Promotion> {
    console.log('调用getPromotionById, id:', id);
    // 确保使用正确的API路径: /api/promotions/{promotionId}
    const apiUrl = `${API_BASE}/${id}`;
    console.log('请求URL:', apiUrl);
    
    try {
      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: this.getHeaders()
      });

      console.log('API响应状态:', response.status, response.statusText);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ message: '解析错误响应失败' }));
        console.error('获取促销活动详情失败:', errorData);
        throw new Error(errorData.message || `获取活动详情失败: ${response.status}`);
      }

      const data = await response.json();
      console.log('getPromotionById API返回数据:', data);
      
      // 确保返回的数据包含必要的字段
      if (!data) {
        console.error('API返回空数据');
        throw new Error('获取活动详情失败: 返回空数据');
      }
      
      // 如果返回的是数组，取第一个元素
      const promotion = Array.isArray(data) ? data[0] : data;
      
      // 确保promotionId字段存在
      if (!promotion.promotionId && promotion.id) {
        console.log(`促销活动 ${promotion.id} 没有promotionId字段，使用id: ${promotion.id}`);
        promotion.promotionId = promotion.id;
      }
      
      return promotion;
    } catch (error) {
      console.error('getPromotionById 发生错误:', error);
      throw error;
    }
  }
  
  static async linkResourcesToPromotion(promotionId: string, resourceIds: string[]): Promise<void> {
    // 使用循环为每个资源创建关联
    for (const resourceId of resourceIds) {
      const response = await fetch(`${API_PATHS.promotionResources}`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify({
          promotionId,
          resourceId
        })
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || `关联资源 ${resourceId} 失败`);
      }
    }
  }

  static async searchPromotions(keyword: string): Promise<Promotion[]> {
    const response = await fetch(`${API_BASE}/search?keyword=${encodeURIComponent(keyword)}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '搜索促销活动失败');
    }

    return response.json();
  }

  static async searchPromotionsByParams(params: { id?: string; title?: string }): Promise<Promotion[]> {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    if (params.id) {
      // 尝试将id转换为数字，以符合后端期望的Long类型
      try {
        const numericId = parseInt(params.id);
        if (!isNaN(numericId)) {
          queryParams.append('id', numericId.toString());
        } else {
          throw new Error('ID必须是数字');
        }
      } catch (error) {
        throw new Error('ID必须是数字');
      }
    }
    if (params.title) queryParams.append('title', params.title);
    
    const response = await fetch(`${API_BASE}/search?${queryParams.toString()}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '搜索促销活动失败');
    }

    return response.json();
  }
}